<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <title>心电数据详情</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="https://cdn.plot.ly/plotly-2.30.0.min.js"></script>
</head>

<body class="bg-gray-100 font-sans min-h-screen">
  <div class="p-6 max-w-6xl mx-auto">
    <!-- 顶部栏 -->
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-semibold text-blue-700">📈 设备 {{ device.device_id }} 的心电数据</h1>
      <button id="backBtn" class="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600">返回</button>
    </div>

    <!-- 无数据提示 -->
    <div id="noData" class="hidden text-center text-gray-600 text-lg bg-white py-10 rounded-lg border border-gray-200 shadow-sm">
      🚫 该设备暂未使用
    </div>

    <!-- 分页列表 -->
    <div id="record-list" class="space-y-3 mb-6"></div>

    <div id="pagination" class="flex justify-center items-center gap-4 mt-4 hidden">
      <button id="prevPage" class="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600">上一页</button>
      <span>第 <span id="currentPage">1</span> / <span id="totalPage">1</span> 页</span>
      <button id="nextPage" class="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600">下一页</button>
    </div>

    <!-- 弹窗 -->
    <div id="ecgModal" class="hidden fixed inset-0 bg-black bg-opacity-60 justify-center items-center z-50">
      <div class="bg-white rounded-xl shadow-lg p-5 w-11/12 max-w-6xl relative">
        <h2 id="recordTitle" class="text-lg font-semibold text-center text-blue-600 mb-4">心电波形图</h2>
        <div id="ecgChart" class="w-full h-[480px]"></div>

        <!-- 缩放模式控制 -->
        <div class="flex justify-between items-center mt-4">
          <div class="flex items-center gap-2">
            <label for="zoomMode" class="text-gray-700 font-medium">缩放模式：</label>
            <select id="zoomMode" class="border rounded px-2 py-1 text-sm">
              <option value="xy">双轴缩放</option>
              <option value="x">仅横轴缩放</option>
              <option value="y">仅纵轴缩放</option>
            </select>
          </div>
          <div class="flex gap-3">
            <button id="resetZoom" class="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600">重置缩放</button>
            <button id="closeModal" class="bg-gray-400 text-white px-3 py-1 rounded hover:bg-gray-500">关闭</button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script>
  window.addEventListener("DOMContentLoaded", function() {
    try {
      var records = JSON.parse('{{ records | tojson | safe }}');
      console.log("记录数:", records.length);

      var listContainer = document.getElementById("record-list");
      var modal = document.getElementById("ecgModal");
      var chartDiv = document.getElementById("ecgChart");
      var titleEl = document.getElementById("recordTitle");
      var pagination = document.getElementById("pagination");
      var noDataEl = document.getElementById("noData");
      var zoomModeSelect = document.getElementById("zoomMode");
      var sampleRate = 250;
      var currentPage = 1;
      var pageSize = 10;
      var totalPage = Math.max(1, Math.ceil(records.length / pageSize));
      var currentTrace = null;

      document.getElementById("backBtn").onclick = function() {
        window.location.href = "/ecg";
      };

      if (!records || records.length === 0) {
        noDataEl.classList.remove("hidden");
        pagination.classList.add("hidden");
        return;
      }

      function renderPage(page) {
        listContainer.innerHTML = "";
        var start = (page - 1) * pageSize;
        var end = Math.min(start + pageSize, records.length);

        for (var i = 0; i < end - start; i++) {
          var rec = records[start + i];
          var index = start + i;
          var endStr = rec.end_time ? " ~ " + rec.end_time : "";
          var div = document.createElement("div");
          div.className = "flex justify-between items-center bg-white border border-gray-300 rounded-lg p-3 hover:bg-blue-50 transition";
          div.innerHTML = "<div class='text-blue-700 font-mono text-base'>" + rec.start_time + endStr + "</div>" +
                          "<button class='view-btn bg-green-500 text-white px-4 py-1 rounded hover:bg-green-600' data-index='" + index + "'>查看</button>";
          listContainer.appendChild(div);
        }

        document.getElementById("currentPage").innerText = currentPage;
        document.getElementById("totalPage").innerText = totalPage;
        pagination.classList.remove("hidden");

        var btns = document.querySelectorAll(".view-btn");
        for (var j = 0; j < btns.length; j++) {
          btns[j].onclick = function(e) {
            var idx = parseInt(e.target.dataset.index);
            showRecord(records[idx]);
          };
        }
      }

      function showRecord(record) {
        if (!record || !record.data || record.data.trim() === "") {
          alert("该记录没有心电数据");
          return;
        }

        var dataArr = record.data.split(",").map(function(v) { return parseFloat(v); }).filter(function(v) { return !isNaN(v); });
        if (dataArr.length === 0) {
          alert("数据格式错误");
          return;
        }

        var startTime = new Date(record.start_time);
        var timeArr = dataArr.map(function(_, i) { return new Date(startTime.getTime() + (i / sampleRate) * 1000); });

        titleEl.textContent = "心电波形图 | " + record.start_time + (record.end_time ? " ~ " + record.end_time : "");
        modal.classList.remove("hidden");
        modal.classList.add("flex");

        setTimeout(function() {
          var trace = {
            x: timeArr,
            y: dataArr,
            mode: "lines",
            line: { color: "rgb(16,185,129)", width: 1 },
            hoverinfo: "x+y",
            name: "心电信号"
          };

          var layout = {
            margin: { l: 60, r: 30, t: 20, b: 50 },
            xaxis: { title: "时间", type: "date", tickformat: "%H:%M:%S", showgrid: true },
            yaxis: { title: "电压 (mV)", range: [-1, 1], showgrid: true },
            dragmode: "pan",
            plot_bgcolor: "white",
            paper_bgcolor: "white"
          };

          var config = {
            responsive: true,
            scrollZoom: true,
            displaylogo: false,
            displayModeBar: true,
            modeBarButtonsToRemove: ["lasso2d", "select2d"]
          };

          Plotly.newPlot(chartDiv, [trace], layout, config);
          currentTrace = { trace: trace, layout: layout };
        }, 200);
      }

      zoomModeSelect.addEventListener("change", function(e) {
        if (!currentTrace) return;
        var mode = e.target.value;
        var fixedX = false, fixedY = false;
        if (mode === "x") fixedY = true;
        else if (mode === "y") fixedX = true;
        Plotly.relayout(chartDiv, { "xaxis.fixedrange": fixedX, "yaxis.fixedrange": fixedY });
      });

      document.getElementById("resetZoom").onclick = function() {
        if (!currentTrace) return;
        Plotly.relayout(chartDiv, { "xaxis.autorange": true, "yaxis.range": [-1, 1] });
      };

      document.getElementById("closeModal").onclick = function() {
        modal.classList.add("hidden");
        modal.classList.remove("flex");
      };

      document.getElementById("prevPage").onclick = function() {
        if (currentPage > 1) {
          currentPage--;
          renderPage(currentPage);
        }
      };

      document.getElementById("nextPage").onclick = function() {
        if (currentPage < totalPage) {
          currentPage++;
          renderPage(currentPage);
        }
      };

      renderPage(currentPage);
    } catch (error) {
      console.error("错误:", error);
      alert("页面加载失败");
      document.getElementById("backBtn").onclick = function() {
        window.location.href = "/ecg";
      };
    }
  });
  </script>
</body>
</html>